﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.Common;
using SharpDiary.Core.Attributes;
using SharpDiary.Core.ORMapping;
using SharpDiary.Core.Utility;

namespace SharpDiary.Task
{
    [GuiModule("21aee42e-c54f-4201-864a-605390dd78fd", "TaskEditor", "Ray Shaw(demogodyou@gmail.com)")]
    public partial class frmTaskEditor : GuiModuleUIBase
    {
        #region Fields & Properties

        private TaskInfoItemControl _linkedItem;

        private TaskInfo _task;

        public TaskInfo Task
        {
            get { return _task; }
            set
            {
                _task = value;
                ShowTaskInfo();
            }
        }

        #endregion

        #region Constructors

        public frmTaskEditor()
        {
            InitializeComponent();

            FillStatus();
            dtpStart.Value = DateTime.Now.Date;
            dtpEnd.Value = dtpStart.Value;

            tabControlMain.SelectedIndex = 0;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

        }

        private void FillStatus()
        {
            cmbStatus.Items.Clear();
            List<TaskStatusInfo> allStatus = TaskStatusInfo.GetAllStatus();

            foreach (TaskStatusInfo status in allStatus)
            {
                cmbStatus.Items.Add(status);
            }

            if (cmbStatus.Items.Count > 0) { cmbStatus.SelectedIndex = 0; }
        }

        #endregion

        #region Methods

        public override void SetParameter(object parameter, object sender)
        {
            base.SetParameter(parameter, sender);

            _linkedItem = sender as TaskInfoItemControl;
            TaskInfo task = parameter as TaskInfo;

            if (task != null) { Task = task; }
        }

        /// <summary>
        /// 显示任务信息。
        /// </summary>
        private void ShowTaskInfo()
        {
            if (_task == null)
            {
                txtName.Text = string.Empty;
                cmbStatus.SelectedIndex = -1;
                dtpStart.Value = DateTime.Now;
                dtpEnd.Value = DateTime.Now;
                txtPlace.Text = string.Empty;
                txtDescription.Text = string.Empty;
                cmbStatus.SelectedIndex = -1;

                return;
            }

            if (cmbStatus.Items.Count == 0) { FillStatus(); }

            //显示任务信息
            txtName.Text = _task.Name;
            cmbStatus.SelectedIndex = FindItemIndex(_task.Status);
            dtpStart.Value = _task.StartDatetime;
            dtpEnd.Value = _task.EndDatetime;
            txtPlace.Text = _task.Place;
            txtDescription.Text = _task.Description;
        }

        private int FindItemIndex(Int64 id)
        {
            for (int i = 0; i < cmbStatus.Items.Count; i++)
            {
                TaskStatusInfo item = cmbStatus.Items[i] as TaskStatusInfo;
                if (item.Id == id)
                {
                    return i;
                }
            }
            return -1;
        }

        public override string GetSettingsKeyName()
        {
            return this.Name;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);


        }

        /// <summary>
        /// 检查数据有效性。
        /// </summary>
        /// <returns></returns>
        private bool CheckIfInputOk()
        {
            if (txtName.Text.Trim().Length == 0)
            {
                popupMessageControl.Show("请输入任务名称。");
                txtName.Focus();
                txtName.SelectAll();

                return false;
            }

            if (cmbStatus.SelectedIndex == -1)
            {
                popupMessageControl.Show("请选择任务状态。");
                cmbStatus.Focus();
                cmbStatus.DroppedDown = true;

                return false;
            }


            /*
            if (dtpStart.Value.Date < DateTime.Now.Date)
            {
                popupMessageControl.Show("任务开始日期不应该是过去的，请设置为现在或将来日期。");
                dtpStart.Focus();

                return false;
            }

            if (dtpEnd.Value.Date < DateTime.Now.Date)
            {
                popupMessageControl.Show("任务开始日期不应该是过去的，请设置为现在或将来日期。");
                dtpEnd.Focus();

                return false;
            }

            */

            if (dtpStart.Value.Date > dtpEnd.Value.Date)
            {
                popupMessageControl.Show("任务结束日期要晚于或等于结束日期。请重新设置结束日期。");
                dtpEnd.Focus();

                return false;
            }

            return true;
        }

        /// <summary>
        /// 保存。
        /// </summary>
        private void Save()
        {
            if (!CheckIfInputOk()) { return; }

            if (_task == null || string.IsNullOrEmpty(_task.Name)) //新增
            {
                _task = new TaskInfo();
                _task.Name = txtName.Text;
                _task.Status = (cmbStatus.SelectedItem as TaskStatusInfo).Id;
                _task.StartDatetime = dtpStart.Value.Date;
                _task.EndDatetime = dtpEnd.Value.Date;
                _task.Place = txtPlace.Text;
                _task.Description = txtDescription.Text;

                if (TaskInfo.Create<TaskInfo>(_task))
                {
                    //通知任务管理窗体刷新显示
                    OwnerShell.NotifyMessage(this, new MessageReceivedEventArgs(MessageDefinition.Refresh,
                        "21aee42e-c54f-4201-864a-605390dd78fd", "3cbe438e-37a3-428a-aae3-a15acc5d47a8"));

                    popupMessageControl.Show("保存成功。");
                    DialogResult = DialogResult.OK;
                    if (_linkedItem != null)
                    {
                        _linkedItem.Task = _task;
                    }

                    timer.Start();
                }
                else
                {
                    popupMessageControl.Show("保存失败。");
                }
            }
            else //更新
            {
                _task.Name = txtName.Text;
                _task.Status = (cmbStatus.SelectedItem as TaskStatusInfo).Id;
                _task.StartDatetime = dtpStart.Value.Date;
                _task.EndDatetime = dtpEnd.Value.Date;
                _task.Place = txtPlace.Text;
                _task.Description = txtDescription.Text;

                if (TaskInfo.Update<TaskInfo>(_task))
                {
                    popupMessageControl.Show("更新成功。");
                    DialogResult = DialogResult.OK;
                    if (_linkedItem != null)
                    {
                        _linkedItem.Task = _task;
                    }

                    timer.Start();
                }
                else
                {
                    popupMessageControl.Show("更新失败。");
                }
            }
        }

        #endregion

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            Close();
        }

        private void miOneDay_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            int days = 0;

            if (item != null && item.Tag != null && int.TryParse(item.Tag.ToString(), out days))
            {
                dtpEnd.Value = dtpStart.Value.AddDays(days).Date;
            }
        }

        private void miOneMonth_Click(object sender, EventArgs e)
        {
            dtpEnd.Value = dtpStart.Value.AddMonths(1);
        }

        private void miOneYear_Click(object sender, EventArgs e)
        {
            dtpEnd.Value = dtpStart.Value.AddYears(1);
        }

        private void lblQuickSetDateRange_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            contextMenuStripQuickSetDateRange.Show(lblQuickSetDateRange, new Point(0, lblQuickSetDateRange.Height),
                ToolStripDropDownDirection.BelowRight);
        }

        private void lblManageTasks_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private void btnManageTasks_Click(object sender, EventArgs e)
        {
            OwnerShell.ExecuteAction("SharpDiary.Task", "3cbe438e-37a3-428a-aae3-a15acc5d47a8");
        }

        private void cmbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            TaskStatusInfo status = cmbStatus.SelectedItem as TaskStatusInfo;
            if (status != null && status.Picture != null && status.Picture.Length > 0)
            {
                lblImageAboveLogo.Image = Utils.BytesToImage(status.Picture);
            }
            else
            {
                lblImageAboveLogo.Image = null;
            }
        }
    }
}
